import Router from 'koa-router'
import { isNil, cloneDeep } from 'lodash-es'
import $dayjs from 'dayjs'
import { promisePool } from '../database/mysql2/index.js'

export const router = new Router()

// 新增与更新前的检查，检查name是否重复
const updateBeforeInspect = async (body, ctx) => {
  const [nameRows] = await promisePool.query(
    `SELECT * FROM company_info WHERE name='${body.name}' AND id!='${body.id}'`
  )
  if (nameRows.length) {
    ctx.body = {
      code: 400,
      msg: '公司名称重复！'
    }
    return true
  }
}

// 新增公司数据
router.post('/api/v1/company', async function (ctx) {
  const body = ctx.request.body
  // console.log(body)
  // 检查name是否重复
  if (await updateBeforeInspect(body, ctx)) return
  await promisePool.execute(
    `INSERT INTO company_info (name,domicile,manager,isNHTE,nhteNumber,isSPSEnterprises,spsAppliTime,isInnovativeSME,smeAppliTime,isSMETech,smeTechAppliTime,status,createTime) values("${
      body.name
    }","${body.domicile}","${body.manager}",${body.isNHTE},"${
      body.nhteNumber
    }",${body.isSPSEnterprises},"${body.spsAppliTime}",${
      body.isInnovativeSME
    },"${body.smeAppliTime}",${body.isSMETech},"${body.smeTechAppliTime}",${
      body.status
    },"${+new Date()}")`
  )

  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})

const getQueryHandle = async (query) => {
  const keywords = isNil(query.keywords) ? '' : query.keywords
  const status =
    isNil(query.status) || query.status === '' ? '0,1' : query.status
  const [rows] = await promisePool.query(
    `SELECT * FROM company_info WHERE status IN (${status}) AND name LIKE '%${keywords}%'`
  )
  return rows
}

const timeDeal = (dataList) => {
  return dataList.map((item) => {
    item.creatTime = item.creatTime
      ? $dayjs(item.creatTime * 1).format('YYYY-MM-DD HH:mm:ss')
      : item.creatTime
    item.updateTime = item.updateTime
      ? $dayjs(item.updateTime * 1).format('YYYY-MM-DD HH:mm:ss')
      : item.updateTime

    return item
  })
}

// 获取公司的数据列表
router.get('/api/v1/company', async function (ctx) {
  const query = ctx.request.query
  // console.log(query)
  const dataList = await getQueryHandle(query)
  // console.log(dataList)
  let newList = dataList.slice(
    query.pageSize * (query.pageNum - 1),
    query.pageSize * query.pageNum
  )
  newList = timeDeal(newList)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: {
      list: newList,
      total: dataList.length
    }
  }
})

// 字典数据-查询所有的
router.get('/api/v1/companys', async function (ctx) {
  const query = ctx.request.query
  // console.log(query)
  let dataList = await getQueryHandle(query)
  dataList = timeDeal(dataList)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: dataList
  }
})
// 查询单个公司数据
router.get('/api/v1/company/:id/form', async function (ctx) {
  const params = ctx.request.params
  console.log(params)
  const [rows] = await promisePool.query(
    `SELECT * FROM company_info WHERE id=${params.id}`
  )
  // console.log(rows)
  ctx.body = {
    code: 200,
    msg: '查询成功！',
    data: rows[0]
  }
})

// 更新数据公司的信息
router.put('/api/v1/company/:id', async function (ctx) {
  const params = ctx.request.params
  const body = ctx.request.body
  console.log(params, body)
  // 检查name是否重复
  if (await updateBeforeInspect(body, ctx)) return
  await promisePool.execute(
    `UPDATE company_info SET name="${body.name}",domicile="${
      body.domicile
    }",manager="${body.manager}",isNHTE=${body.isNHTE},nhteNumber="${
      body.nhteNumber
    }",isSPSEnterprises=${body.isSPSEnterprises},spsAppliTime="${
      body.spsAppliTime
    }",isInnovativeSME=${body.isInnovativeSME},smeAppliTime="${
      body.smeAppliTime
    }",isSMETech=${body.isSMETech},smeTechAppliTime="${
      body.smeTechAppliTime
    }",status=${body.status},updateTime="${+new Date()}" WHERE id='${body.id}'`
  )
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})

// 删除单个或多个数据的信息
router.delete('/api/v1/company/:id', async function (ctx) {
  const params = ctx.request.params
  console.log(params)
  const [ResultSetHeader] = await promisePool.execute(
    `DELETE FROM company_info WHERE id IN (${params.id})`
  )
  console.log('ResultSetHeader=', ResultSetHeader)
  ctx.body = {
    code: 200,
    msg: '操作成功！',
    data: null
  }
})
